package com.lizardmind.haofudoctor.ui.diagnosis.visit

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.constraint.ConstraintLayout
import android.support.v7.widget.GridLayoutManager
import android.view.View
import android.widget.LinearLayout
import com.blankj.utilcode.util.TimeUtils
import com.linxiao.framework.activity.BaseActivity
import com.linxiao.framework.util.color
import com.linxiao.framework.util.toasts
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.databinding.ItemDiyVisitTiemDateBinding
import com.lizardmind.haofudoctor.databinding.ItemDiyVisitTiemDayBinding
import com.lizardmind.haofudoctor.databinding.ItemDiyVisitTiemHeadBinding
import com.lizardmind.haofudoctor.manager.postApi
import com.lizardmind.haofudoctor.other.*
import com.lizardmind.haofudoctor.other.rongYun.FanganTipsMessage
import com.lizardmind.haofudoctor.other.rongYun.MessageTags
import com.lizardmind.haofudoctor.other.rongYun.USER_PREFIX
import io.reactivex.functions.Consumer
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import kotlinx.android.synthetic.main.include_title_right_text.*
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.backgroundColor
import org.jetbrains.anko.include
import org.jetbrains.anko.linearLayout
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.toast
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

/**
 * 自定义随访时间 界面
 * Created by Extends on 2017/12/12 11:15
 */
class DiyVisitTimeActivity:BaseActivity() {
    var currDayBean : DvtDayBean? = null
    var ceiling:Long = 0//时间上限
    var lower:Long = 0//时间下限
    val format1 = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    val pid by lazy { intent.getStringExtra("pid")?:"1" }//开方id
    val custom_time by lazy { intent.getIntExtra("custom_time",0)}//开方自定义随访时间
    val create_time by lazy { intent.getIntExtra("create_time",0)}//开方创建时间
    val rUid by lazy { intent.getStringExtra("rUid") }
    private val apt by lazy { MultiTypeAdapter().apply {
        register<DvtHeadBean, ItemDiyVisitTiemHeadBinding>(R.layout.item_diy_visit_tiem_head)
        register<DvtDateBean, ItemDiyVisitTiemDateBinding>(R.layout.item_diy_visit_tiem_date)
        register<DvtDayBean, ItemDiyVisitTiemDayBinding>(R.layout.item_diy_visit_tiem_day).apply {
            onBind = {itemBinding, data ->
                itemBinding.root.onClick {
                    if(data.day.isNotEmpty()&&data.date in (ceiling..lower)){
                        data.isSelect=!data.isSelect
                        if(data.isSelect){
                            currDayBean?.isSelect=false
                            currDayBean = data
                        }else{
                            currDayBean=null
                        }
                        notifyDataSetChanged()
                    }
                }
            }
        }
    }}
    private val item = Items()
    override fun onCreatRootView(): View? {
        return linearLayout {
            orientation = LinearLayout.VERTICAL
            backgroundColor = color(R.color.white)
            include<ConstraintLayout>(R.layout.include_title_right_text)
            recyclerView {
                id = R.id.test_recycler
                layoutManager = GridLayoutManager(context,7).apply {
                    spanSizeLookup = object :GridLayoutManager.SpanSizeLookup(){
                        override fun getSpanSize(position: Int): Int {
                            return when(item[position]){
                                is DvtDateBean->7
                                else -> 1
                            }
                        }
                    }
                }
                adapter = apt
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    override fun onInitView(savedInstanceState: Bundle?) {
        imgLeft.setImageResource(R.mipmap.back)
        imgLeft.onClick { finish() }
        titleText.text = "自定义随访复诊时间"
        tvRight.text="确定"
        tvRight.onClick {
            if(currDayBean==null){
                toast("当前没有选中")
                return@onClick
            }
            observe {
                val ct = (currDayBean!!.date/1000).toString()
                val cts = SimpleDateFormat("yyyy年MM月dd日").format(Date(currDayBean!!.date))
                postApi<Request<String>>(hashMapOf("action" to "custom_visit_time",
                        "token" to DoctorInfo.token,"id" to pid,"custom_time" to ct),
                        Consumer {
                            it.dispose {
                                //消息通过网络发送成功的回调
                                RongIM.getInstance().sendMessage(
                                        Message.obtain(rUid, Conversation.ConversationType.PRIVATE, FanganTipsMessage(jsonOf("id" to pid,"endTime" to cts,"custom" to "1"))),
                                        MessageTags.FANGAN_TIPS,
                                        null,
                                        object : io.rong.imlib.IRongCallback.ISendMessageCallback {
                                            override fun onAttached(p0: Message) {}
                                            override fun onSuccess(p0: Message) {
                                                toasts("设置成功")
                                                finish()
                                            }
                                            override fun onError(p0: Message?, p1: RongIMClient.ErrorCode) {}
                                        }
                                )
                            }
                        })
            }
        }
        initTime(create_time,custom_time)
    }

    /**
     * 初始化时间
     */
    fun initTime(createTime:Int,customTime:Int){
        val s = "日一二三四五六"
        apt.items = item.apply {
            s.map {
                add(DvtHeadBean(it.toString()))
            }
            val date = Calendar.getInstance()
            val millis1 =date.timeInMillis//当前日期
            val time2 = format1.format(Date(customTime*1000L)).split("-")
            date.set(time2[0].toInt(),time2[1].toInt()-1,time2[2].toInt())//设置默认的
            val millis2 = date.timeInMillis//自定义的时间
            val time = format1.format(Date(createTime*1000L)).split("-")
            date.set(time[0].toInt(),time[1].toInt()-1,time[2].toInt())//设置开方时的创建时间
            val d0 = time[2].toInt()//开方时的时间
            val date1 = date.clone() as Calendar
            date1.add(Calendar.DAY_OF_MONTH,30)
            date1.set(Calendar.DAY_OF_MONTH,date1.getActualMaximum(Calendar.DAY_OF_MONTH))//设置结束月的最大天数
            val d2 = d0+30//可选的结束时间
            date.set(Calendar.DAY_OF_MONTH,1)//设置开方月份的第一天
            val d1 = ((millis1-date.timeInMillis)/(24*60*60*1000)).toInt()+1//今天
            val days = ((date1.timeInMillis-date.timeInMillis)/(24*60*60*1000)).toInt()+1//总共的天数
            val d3 = ((millis2-date.timeInMillis)/(24*60*60*1000)).toInt()+1//预先设置的天数

            val format = SimpleDateFormat("yyyy年MM月", Locale.getDefault())
            (1 .. days).forEach {
                val d = date.get(Calendar.DAY_OF_MONTH)
                if(d == 1){//如果是月份第一天，则先添加空白格子
                    add(DvtDateBean(format.format(date.time)))
                    val w1 = date.get(Calendar.DAY_OF_WEEK)
                    (0 until w1-1).forEach { add(DvtDayBean("",0)) }
                }
                when (it) {
                    d1 -> add(DvtDayBean("今天",date.timeInMillis))
                    d0->add(DvtDayBean("开始",date.timeInMillis))
                    in (d1 + 1)..(d2) -> {
                        val dvt = DvtDayBean(d.toString(),date.timeInMillis,true, it==d3)
                        if(dvt.isSelect){
                            currDayBean = dvt
                        }
                        add(dvt)
                        if(it == d1+1){
                            ceiling = date.timeInMillis
                        }
                        if(it == d2){
                            lower = date.timeInMillis
                        }
                    }
                    else -> add(DvtDayBean(d.toString(),date.timeInMillis))
                }
                date.add(Calendar.DAY_OF_MONTH,1)
            }
        }
        apt.notifyDataSetChanged()
    }
}